package com.mall.common.controller;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.mall.common.bean.User;
import com.mall.common.domain.manage.Menu;
import com.mall.common.domain.manage.Operate;
import com.mall.common.exception.NoticeException;
import com.mall.common.service.MenuService;
import com.mall.common.service.OperateService;
import com.mall.common.service.RoleService;
import com.mall.common.util.AppContext;
import com.mall.common.util.RegexpHelper;
import com.mall.common.util.RequestUtils;
import com.mall.common.util.ResponseUtils;
import com.mall.common.validation.annotation.IntRangeFieldValidator;
import com.mall.common.validation.annotation.RequiredFieldValidator;
import com.mall.common.validation.annotation.RequiredStringValidator;
import com.mall.common.validation.annotation.Validations;

@Controller
@RequestMapping("/admin/system/operate")
public class OperateController extends BaseController {
	
	@Resource private OperateService operateService;
	@Resource private MenuService menuService;
	@Resource private RoleService roleService;

	@RequestMapping(value="/add", method=RequestMethod.GET)
	public String add(Long id, Model model) {
		Menu menu = menuService.find(id);
		model.addAttribute("menu", menu);
		return "/admin/system/menu/operateAdd";
	}

	@Validations(
			requiredStrings = {
					@RequiredStringValidator(fieldName="name",message="操作名称不能为空")
			},
			requiredFields = {
					@RequiredFieldValidator(fieldName="menu_id",message="所属菜单不存在"),
					@RequiredFieldValidator(fieldName="isDiaplayInToolBar",message="是否显示在表格工具栏上不能为空"),
					@RequiredFieldValidator(fieldName="type",message="动作类型不能为空")
			},
			intRangeFields = {
					@IntRangeFieldValidator(fieldName="type",min="1",max="2",message="动作类型不正确")
			}
	)
	@RequestMapping(value="/add", method=RequestMethod.POST)
	public String add(Operate operate, Long menu_id, RedirectAttributes redirectattributes) {
		operate.setMenu(menuService.find(menu_id));
		if(!validate(operate)){
			return "/admin/system/common/error";
		}else{
			operateService.persist(operate);
			redirect(redirectattributes, successMessage);
			return "redirect:/admin/system/menu/detail.jhtml?id=" + menu_id;
		}
	}
	
	@RequestMapping(value="/update/{id}", method=RequestMethod.GET)
	public String update(@PathVariable Long id, Model model) {
		Operate operate = operateService.find(id);
		model.addAttribute("operate", operate);
		model.addAttribute("menu", operate.getMenu());
		return "/admin/system/menu/operateAdd";
	}

	@Validations(
			requiredStrings = {
					@RequiredStringValidator(fieldName="name",message="操作名称不能为空")
			},
			requiredFields = {
					@RequiredFieldValidator(fieldName="id",message="操作不存在"),
					@RequiredFieldValidator(fieldName="menu_id",message="所属菜单不存在"),
					@RequiredFieldValidator(fieldName="isDiaplayInToolBar",message="是否显示在表格工具栏上不能为空"),
					@RequiredFieldValidator(fieldName="type",message="动作类型不能为空")
			},
			intRangeFields = {
					@IntRangeFieldValidator(fieldName="type",min="1",max="2",message="动作类型不正确")
			}
	)
	@RequestMapping(value="/update", method=RequestMethod.POST)
	public String update(Operate operate, Long menu_id, RedirectAttributes redirectattributes) {
		operate.setMenu(menuService.find(menu_id));
		if(!validate(operate)){
			return "/admin/system/common/error";
		}else{
			operateService.update(operate);
			redirect(redirectattributes, successMessage);
			return "redirect:/admin/system/menu/detail.jhtml?id=" + menu_id;
		}
	}
	
	@RequestMapping(value="/delete/{id}", method=RequestMethod.GET)
	public String delete(@PathVariable Long id) {
		Operate operate = operateService.find(id);
		String result = "redirect:/admin/system/menu/detail.jhtml";
		if(operate != null){
			Menu menu = operate.getMenu();
			if(menu != null){
				result =  "redirect:/admin/system/menu/detail.jhtml?id=" + menu.getId();
			}
			operateService.delete(id);
		}
		return result;
	}
	
	@RequestMapping(value="/toolBarButton", method=RequestMethod.POST)
	@ResponseBody
	public List<Operate> toolBarButton(HttpServletRequest request, HttpServletResponse response){
		String url = RequestUtils.getQueryParam(request, "url");
		
		//如果url中包含了工程路径
		String contextPath = AppContext.getContextPath();
		if(!"".equals(contextPath) && url.indexOf(contextPath) != -1){
			url = url.substring(contextPath.length());
		}
		
		//如果url中包含"/"，则表明是整路径
		if(url.indexOf("/") == -1){
			String path = AppContext.getRequest().getRequestURI().substring(contextPath.length() + 1);
			path = StringUtils.substringBeforeLast(path, "/");
			url = path + "/" + url;
		}
		
		//获取系统所有动作
		List<Operate> allOperateList = operateService.getOperatesWidthCondition(null, -1);
		Operate curOperate = null;
		for(Operate paraOperate : allOperateList){
			String pattern = paraOperate.getPattern();
			if(StringUtils.isEmpty(pattern)){
				pattern = paraOperate.getUrl();
			}
			if(pattern != null && StringUtils.isNotEmpty(pattern) && 
					RegexpHelper.isGlobmatches(url, pattern)){
				curOperate = paraOperate;
				break;
			}
		}
		if(curOperate == null || curOperate.getMenu() == null){
			return null;
		}
		
		List<Long> roleIds = null;
		User cur_user = getUser();
		if(cur_user != null && !cur_user.isSystemManager()){
			roleIds = cur_user.getRoleListIds();
		}
		
		List<Operate> privOperates = operateService.getPrivOperates(roleIds, curOperate.getMenu(), true);
		return privOperates;
	}
	

	@Validations(
		requiredFields = {
			@RequiredFieldValidator(fieldName = "ids", message = "ID非法!"),
			@RequiredFieldValidator(fieldName = "priority", message = "排序非法!")
		}
	)
	@RequestMapping(value="/updateOperatePriority", method=RequestMethod.POST)
	public String updateOperatePriority(Long[] ids, Integer[] priority, HttpServletResponse response){
		if(ids.length != priority.length){
			throw new NoticeException("ids长度与排序的长度不一致!");
		}
		operateService.updatePriority(ids, priority);
		return ResponseUtils.renderJSON(successMessage, response);
	}
}
